package com.lxw.nonghe.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.lxw.nonghe.annotation.RequiresPermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
    private static final String PERMISSION_KEY_PREFIX = "permission:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token is missing");
            return false;
        }

        token = token.substring(7);
        try {
            // 设置当前请求的 Token 值
            StpUtil.setTokenValue(token);
            // 验证登录状态
            StpUtil.checkLogin();

            // 权限检查
            if(handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                RequiresPermission classAnnotation = handlerMethod.getBeanType()
                        .getAnnotation(RequiresPermission.class);

                if(classAnnotation != null) {
                    Long userId = StpUtil.getLoginIdAsLong();
                    // 从Redis获取权限列表
                    List<String> permissions = (List<String>) redisTemplate.opsForValue()
                            .get(PERMISSION_KEY_PREFIX + userId);

                    if(permissions == null || !permissions.contains(classAnnotation.value())) {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        response.getWriter().write("无权限访问");
                        return false;
                    }

                    log.info("Checking permission for user: {}, required: {}, has permissions: {}",
                            userId, classAnnotation.value(), permissions);
                }
            }

            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("过期或无效的 token");
            return false;
        }
    }
}
